package com.ciwong.epaper.modules.evaluate.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.TimeoutError;
import com.ciwong.ciwongwrite.utils.CWUtils;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.epaper.adapter.SubmitPhotoGridAdapter;
import com.ciwong.epaper.modules.epaper.adapter.TeacherDKAdapter;
import com.ciwong.epaper.modules.epaper.adapter.UserDKImgGridViewAdapter;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.epaper.util.PeterTimeCountRefresh;
import com.ciwong.epaper.modules.evaluate.bean.DKAnswer;
import com.ciwong.epaper.modules.evaluate.bean.DKWorkDays;
import com.ciwong.epaper.modules.evaluate.bean.DkWorkDetail;
import com.ciwong.epaper.modules.evaluate.bean.DoDKWorkInfo;
import com.ciwong.epaper.util.ALiYunManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IVUtils;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.KHBVideo.KHBVideoPlayer;
import com.ciwong.epaper.util.KHBVideo.KHBVideoPlayerStandard;
import com.ciwong.epaper.util.ViewUtil;
import com.ciwong.epaper.widget.PlayStateDubView;
import com.ciwong.epaper.widget.PlayStateView;
import com.ciwong.epaper.widget.toast.ZToast;
import com.ciwong.libs.audio.recorder.Mp3Recorder;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.StringUtils;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.utils.BaseJumpManager;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.utils.fileprovider.FileProvider7;
import com.ciwong.mobilelib.widget.BottomMenuDialog;
import com.ciwong.mobilelib.widget.CWDialog;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 打卡作业提交页面
 */
public class UserDkSubmitActivity extends BaseActivity implements View.OnClickListener {


    /**
     * 跳转码，拍照
     */
    public static final int REQUEST_CODE_CAMERA = 0x0000011;

    /**
     * 跳转码，录像
     */
    public static final int ACTION_VIDEO_CAPTURE = 0x0000013;

    protected boolean isRecordFail = false;

    /**
     * 跳转码，相册
     */
    public static final int REQUEST_CODE_ALBUM = 0x0000012;

    public static final int REQUEST_VIDEO_CODE = 0x0000014;
    private boolean isPlayVideo = false;

    private File tempFile = new File(ESystem.getUploadImgPath(),
            getPhotoFileName());

    private File videoFile = new File(ESystem.getUploadImgPath(), getVideoFileName());

    private PlayStateView user_dk_audio_StateView;
    private RelativeLayout user_dk_audio_StateView_lay;
    private TextView user_dk_audio_complete;

    private EditText user_dk_edit_work;

    private TextView user_dk_tex_editStatus;

    private ImageView user_dk_pictures_img;

    private ImageView symbolVideoPlay;

    private Boolean isPlayer = false;

    private PlayStateDubView mLastPlayIcon;

    private RelativeLayout user_dk_submit;
    private List<String> subList;
    private String subVideoPath = "";
    private String subImgPath;
    private List<String> subPicList = new ArrayList<>();
    private String audioPath = "";
    private boolean isRecord = false;
    /**
     * 展开收起
     */
    private TextView user_dk_zk_twxt;

    /**
     * 判断展开收起状态
     */
    private Boolean isZkOrSq = true;

    private String editText = "";


    /**
     * 视频本地保存地址
     */
    private String localVideoPath;
    /**
     * 视频地址
     */
    private String videoUri;

    private boolean isCheckSubmit = false;

    private List<String> alyunPicUriList = new ArrayList<>();
    private String alyunPicUri;
    private String aliyunAudioUri;
    private String aliyunVideoUri;

    private DkWorkDetail dkWorkDetail;
    private SubmitPhotoGridAdapter submitPhotoGridAdapter;
    private MediaPlayer mediaPlayer;
    private MediaPlayer subPlayer;
    private MediaPlayer comPlayer;
    private Uri photoUri;
    private Uri submitVideoUri;
    private int durationLong;
    private String durationStr;
    private String durationAudios;
    protected Mp3Recorder mp3Recorder;

    int picCount;
    int audioCount;
    int videoCount;

    /**
     * 1为拍照 2为录像
     */
    private int videoOrPhoto;

    private KHBVideoPlayerStandard mKHBVideoPlayerStandard;

    private MediaRecorder mediaRecorder;
    private File audioFile;
    private String filePath;
    private double mVolume = -1.0;


    /**
     * 弹框
     */
    private BottomMenuDialog bottomMenuDialog;

    // private CWDialog cwDialog;

    private LinearLayout user_dk_layout;

    private final static String TAG_IMAGE = "tag_image";
    private final static String TAG_VIDEO = "tag_video";
    private final static String TAG_AUDIO = "tag_audio";

    // 使用系统当前日期加以调整作为照片的名称
    public static String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'photo'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";
    }

    public static String getVideoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'video'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".mp4";
    }

    public static String getAudioFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'audio'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".mp3";
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isRecordFail) {
            //录音停止，回传所需要数据
            isRecordFail = false;
            File file = new File(audioPath);
            if (file.exists()) {
                file.delete();
            }
        }
    }

    /**
     * 监听上传
     */
    private ALiYunManager.ALiYunListener aLiYunListener = new ALiYunManager.ALiYunListener() {

        @Override
        public void onProgress(Object tag, long currentSize, long totalSize) {
            if (tag != null) {
                try {
                    String photoPath = tag.toString();
                    if (TAG_VIDEO.equals(photoPath)) {
                        if (currentSize > 0 && totalSize > 0) {
                            long progress = currentSize * 100 / totalSize;
                            if (progress < 100) {
                                updateDownloadProgress((int) progress);
                            }
                        }
                    } else if (TAG_IMAGE.equals(photoPath)) {
                        if (currentSize > 0 && totalSize > 0) {
                            long progress = currentSize * 100 / totalSize;
                            if (progress < 100) {
                                updateDownloadProgress((int) progress);
                            }
                        }
                    } else if (TAG_AUDIO.equals(photoPath)) {
                        if (currentSize > 0 && totalSize > 0) {
                            long progress = currentSize * 100 / totalSize;
                            if (progress < 100) {
                                updateDownloadProgress((int) progress);
                            }
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


        @Override
        public void onSuccess(Object tag, String url) {
            CWLog.d("aliyunListener", "上传完成url=" + url + "&tag=" + tag);
            if (tag != null) {
                try {
                    String photoPath = tag.toString();
                    if (TAG_VIDEO.equals(photoPath)) {
                        aliyunVideoUri = url;
                        // 上传成功
                        isCheckSubmit = true;
                        videoCount--;
                        //hideDownloadHorizontalProgressBar();

                    } else if (TAG_IMAGE.equals(photoPath)) {

                        alyunPicUriList.add(url);
                        picCount--;

                        //dkAnswer.setPictures(path);
                    } else if (TAG_AUDIO.equals(photoPath)) {
                        aliyunAudioUri = url;
                        audioCount--;
                    }
                    CWLog.d("aliyunListener", "picCount=" + picCount + "&videoCount=" + audioCount + "&audioCount=" + audioCount);
                    if (videoCount == 0 && audioCount == 0 && picCount == 0) {
                        submitDK();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(Object tag, int errorCode) {
            if (tag != null) {
                try {
                    String photoPath = String.valueOf(tag);
                    if (photoPath.equals(subVideoPath)) {
                        hideDownloadProgress();
                        videoCount--;
                        ZToast.makeText(UserDkSubmitActivity.this,
                                "上传失败，请稍后重试！", ZToast.LENGTH_SHORT).show();
                    } else if (photoPath.equals(subImgPath)) {
                        hideDownloadProgress();
                        picCount--;
                        ZToast.makeText(UserDkSubmitActivity.this,
                                "上传失败，请稍后重试！", ZToast.LENGTH_SHORT).show();
                    } else if (photoPath.equals(audioPath)) {
                        hideDownloadProgress();
                        audioCount--;
                        ZToast.makeText(UserDkSubmitActivity.this,
                                "上传失败，请稍后重试！", ZToast.LENGTH_SHORT).show();
                    }
                    if (videoCount == 0 && audioCount == 0 && picCount == 0) {
                        submitDK();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    };

    public void submitDK() {
        hideDownloadProgress();
        int classId = (int) EApplication.getInstance().getClazz().getClassId();
        int brandId = EApplication.BRAND_ID;
        DKAnswer newDKAnswer = new DKAnswer();
        newDKAnswer.setClassId(classId);
        newDKAnswer.setBrandId(brandId);
        newDKAnswer.setContent(user_dk_edit_work.getText().toString());
        if (dkWorkDetail.getDkworkdays() != null) {
            DKWorkDays dkWorkDays = dkWorkDetail.getDkworkdays().get(postion);
            newDKAnswer.setDateId(dkWorkDays.getDateId());
        }
        newDKAnswer.setWorkId(dkWorkDetail.getWorkId());
        newDKAnswer.setUserId(dkWorkDetail.getMyDkWork().getUserId());
        newDKAnswer.setUserName(dkWorkDetail.getMyDkWork().getUserName());
        long nowTime = System.currentTimeMillis();
        newDKAnswer.setCreateTime(nowTime);
        newDKAnswer.setVedios(aliyunVideoUri);
        newDKAnswer.setAudios(aliyunAudioUri);
        for (int i = 0; i < alyunPicUriList.size(); i++) {
            if (i == 0) {
                alyunPicUri = alyunPicUriList.get(i);
            } else {
                alyunPicUri = alyunPicUri + "," + alyunPicUriList.get(i);
            }

        }
        newDKAnswer.setPictures(alyunPicUri);

        EpaperDao.getInstance().submitDkWork(newDKAnswer, new BaseExtCallBack(UserDkSubmitActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(int errorCode, Object data) {
                hideCricleProgress();
                super.failed(errorCode, data);
                failed(data);

            }

            @Override
            public void failed(Object data) {
                if (data instanceof TimeoutError) {
                    hideCricleProgress();
                    ToastUtil.INSTANCE.toastCenterError("提交失败，请稍后再试");
                }

            }

            @Override
            public void success(Object data) {
                ToastUtil.INSTANCE.toastCenterSuccess("提交打卡作业成功");
                hideCricleProgress();
                getUserDkWorkDetails(dkWorkDetail.getWorkId());
                //EpaperJumpManager.jumpToUserDKWorkActivity(UserDkSubmitActivity.this,dkWorkDetail.getWorkId(),R.string.go_back);

            }
        });
    }


    private String downloadMsg = "视频处理中...";

    /**
     * 上传视频到阿里云
     */
    private final void submitVideo() {
        File localMixDubVideoFile = new File(subVideoPath);
        if (localMixDubVideoFile.exists()) {
            downloadMsg = "上传中，请稍等...";
            showDownloadProgress(downloadMsg);
            String VideoUrlKey = ALiYunManager.getInstance()
                    .getDkworKey(subVideoPath);
            ALiYunManager.getInstance().addDKFile(subVideoPath,
                    VideoUrlKey, TAG_VIDEO);
        } else {
            ZToast.makeText(UserDkSubmitActivity.this, "视频不存在，请重新提交",
                    ZToast.LENGTH_SHORT).show();
        }

    }

    public void setSubmitImg() {
        if (uriList.size() == 0 && "".equals(subVideoPath)) {
            dk_sub_lay.setVisibility(View.GONE);
        } else {
            dk_sub_lay.setVisibility(View.VISIBLE);
        }
        if (null != subVideoPath && !"".equals(subVideoPath)) {
            user_dk_grid_submit.setNumColumns(2);
        } else {
            user_dk_grid_submit.setNumColumns(3);
        }
        if (null != uriList && uriList.size() == 1) {
            user_dk_grid_submit.setVisibility(View.VISIBLE);
            user_dk_pictures_img.setImageResource(R.drawable.user_dk_pictures_img);
            user_dk_pictures_img.setOnClickListener(this);
            submitPhotoGridAdapter = new SubmitPhotoGridAdapter(UserDkSubmitActivity.this, uriList, subPicList, subVideoPath);
            user_dk_grid_submit.setAdapter(submitPhotoGridAdapter);
        } else if (uriList.size() == 9) {
            user_dk_grid_submit.setVisibility(View.VISIBLE);
            user_dk_pictures_img.setImageResource(R.drawable.user_dk_pic_no);
            submitPhotoGridAdapter = new SubmitPhotoGridAdapter(UserDkSubmitActivity.this, uriList, subPicList, subVideoPath);
            user_dk_grid_submit.setAdapter(submitPhotoGridAdapter);
            user_dk_pictures_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ToastUtil.INSTANCE.toastCenterError("已达图片上传上限");
                }
            });
        } else if (uriList.size() > 0 && uriList.size() < 10) {
            //submitPhotoGridAdapter.listAdd(uri);
            user_dk_grid_submit.setVisibility(View.VISIBLE);
            user_dk_pictures_img.setImageResource(R.drawable.user_dk_pictures_img);
            user_dk_pictures_img.setOnClickListener(this);
            submitPhotoGridAdapter = new SubmitPhotoGridAdapter(UserDkSubmitActivity.this, uriList, subPicList, subVideoPath);
            user_dk_grid_submit.setAdapter(submitPhotoGridAdapter);
        } else {
            user_dk_grid_submit.setVisibility(View.GONE);
            user_dk_pictures_img.setOnClickListener(this);
        }
    }

    public void setSubVideo() {
        if (uriList.size() == 0 && "".equals(subVideoPath)) {
            dk_sub_lay.setVisibility(View.GONE);
        } else {
            dk_sub_lay.setVisibility(View.VISIBLE);
        }
        if (null != subVideoPath && !"".equals(subVideoPath)) {
            delete_video_view.setVisibility(View.VISIBLE);
            if (subPicList.size() > 0) {
                user_dk_grid_submit.setNumColumns(2);
                submitPhotoGridAdapter = new SubmitPhotoGridAdapter(UserDkSubmitActivity.this, uriList, subPicList, subVideoPath);
                user_dk_grid_submit.setAdapter(submitPhotoGridAdapter);

            }
            delete_video_view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    subVideoPath = "";
                    user_dk_grid_submit.setNumColumns(3);
                    submitPhotoGridAdapter = new SubmitPhotoGridAdapter(UserDkSubmitActivity.this, uriList, subPicList, subVideoPath);
                    user_dk_grid_submit.setAdapter(submitPhotoGridAdapter);
                    user_dk_video_img.setOnClickListener(UserDkSubmitActivity.this);
                    r2_dub_video.setVisibility(View.GONE);
                    user_dk_video_img.setImageDrawable(UserDkSubmitActivity.this.getResources().getDrawable(R.drawable.user_dk_video_img));
                }
            });
            user_dk_video_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ToastUtil.INSTANCE.toastCenterError("只能上传一段视频");
                }
            });
            r2_dub_video.setVisibility(View.VISIBLE);
            user_dk_video_img.setImageDrawable(this.getResources().getDrawable(R.drawable.user_dk_video_no));
            user_dk_video_submit.setplsyModeUrlUp(subVideoPath, KHBVideoPlayer.SCREEN_LAYOUT_LIST, KHBVideoPlayer.PLAY_MODE_UNMUTE, "");
        } else {
            if (subPicList.size() > 0) {
                user_dk_grid_submit.setNumColumns(3);
                submitPhotoGridAdapter = new SubmitPhotoGridAdapter(UserDkSubmitActivity.this, uriList, subPicList, subVideoPath);
                user_dk_grid_submit.setAdapter(submitPhotoGridAdapter);

            }
            delete_video_view.setVisibility(View.GONE);
            delete_video_view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                }
            });
            user_dk_video_img.setOnClickListener(this);
            user_dk_video_img.setImageDrawable(this.getResources().getDrawable(R.drawable.user_dk_video_img));
            r2_dub_video.setVisibility(View.GONE);
        }
    }

    @SuppressLint("NewApi")
    public String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    public boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }


    public boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    public String getDataColumn(Context context, Uri uri, String selection,
                                String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            Uri outPuturi;
            android.content.Intent intent = new Intent();
            switch (requestCode) {
                case REQUEST_VIDEO_CODE:
                    if (data != null) {
                        submitVideoUri = data.getData();
                        //subVideoPath = getPath(this, submitVideoUri);
                        subVideoPath = FileUtil.uriToFileApiQ(submitVideoUri, UserDkSubmitActivity.this).getAbsolutePath();
                        /*String[] filePathColumn = {MediaStore.Video.Media.DATA};

                        Cursor cursor = getContentResolver().query(submitVideoUri,
                                filePathColumn, null, null, null);
                        cursor.moveToFirst();

                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        subVideoPath = cursor.getString(columnIndex);*/

                        //cursor.close();
                        setSubVideo();
                    }
                    break;

                case REQUEST_CODE_CAMERA:
                    photoUri = FileProvider7.getUriForFile(this, tempFile);
                    //photoUri = data.getData();
                    if (photoUri != null) {
                        subImgPath = tempFile.getPath();
                        subPicList.add(subImgPath);
                        uriList.add(photoUri.toString());
                        setSubmitImg();

                    }
                    break;
                case REQUEST_CODE_ALBUM:
                    if (data != null) {
                        if (videoOrPhoto == 1) {
//                            List<Uri> result = Matisse.obtainResult(data);
//                            for (int i = 0; i < result.size(); i++) {
//                                Uri path = result.get(i);
//                                String[] filePathColumn = {MediaStore.Images.Media.DATA};
//                                Cursor cursor = getContentResolver().query(path,
//                                        filePathColumn, null, null, null);
//                                cursor.moveToFirst();
//                                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//                                subImgPath = cursor.getString(columnIndex);
//                                subPicList.add(subImgPath);
//                                uriList.add(path.toString());
//                                cursor.close();
//                            }
                            if (data.getClipData() != null) {
                                int count = data.getClipData().getItemCount();
                                int newCount = 9 - uriList.size();
                                for (int i = 0; i < newCount && i < count; i++) {
                                    Uri imageUri = data.getClipData().getItemAt(i).getUri();
                                    subImgPath = FileUtil.uriToPicturesFileApiQ(imageUri, UserDkSubmitActivity.this).getAbsolutePath();
                                    subPicList.add(subImgPath);
                                    uriList.add(imageUri.toString());
                                }
                            } else if (data.getData() != null) {
                                Uri imageUri = data.getData();
                                if (uriList.size() < 9) {
                                    subImgPath = FileUtil.uriToPicturesFileApiQ(imageUri, UserDkSubmitActivity.this).getAbsolutePath();
                                    subPicList.add(subImgPath);
                                    uriList.add(imageUri.toString());
                                }
                            }
                            setSubmitImg();
                        } else {
                            submitVideoUri = data.getData();
                            String[] filePathColumn = {MediaStore.Video.Media.DATA};

                            Cursor cursor = getContentResolver().query(submitVideoUri,
                                    filePathColumn, null, null, null);
                            cursor.moveToFirst();

                            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                            subVideoPath = cursor.getString(columnIndex);
                            cursor.close();
                            setSubVideo();
                        }

                    }
                    break;
                case ACTION_VIDEO_CAPTURE:
                    if (data != null) {
//                        submitVideoUri = data.getData();
//                        String[] filePathColumn = {MediaStore.Video.Media.DATA};
//
//                        Cursor cursor = getContentResolver().query(submitVideoUri,
//                                filePathColumn, null, null, null);
//                        cursor.moveToFirst();
//
//                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//                        subVideoPath = cursor.getString(columnIndex);
//                        cursor.close();
                        subVideoPath = videoFile.getAbsolutePath();
                        setSubVideo();
                        //user_dk_video_submit.startVideo(KHBVideoPlayer.PLAY_MODE_UNMUTE);
                    }
                    break;
            }
        }
    }

    /**
     * 上传图片到阿里云
     */
    private final void submitPic(String uri) {
        File localImgFile = new File(uri);
        if (localImgFile.exists()) {
            downloadMsg = "上传中，请稍等...";
            showDownloadProgress(downloadMsg);
            String photoUrlKey = ALiYunManager.getInstance()
                    .getDkworKey(uri);
            ALiYunManager.getInstance().addDKFile(uri, photoUrlKey,
                    TAG_IMAGE);
        } else {
            ZToast.makeText(UserDkSubmitActivity.this, "图片不存在，请重新提交",
                    ZToast.LENGTH_SHORT).show();
        }

    }

    /**
     * 上传音频
     *
     * @param
     * @param
     */
    public final void addResult() {
        File localImgFile = new File(audioPath);
        if (localImgFile.exists()) {
            String photoUrlKey = ALiYunManager.getInstance()
                    .getDkworKey(audioPath);
            ALiYunManager.getInstance().addDKFile(audioPath, photoUrlKey,
                    TAG_AUDIO);
            CWLog.d("aliyun", "提交" + System.currentTimeMillis() + "tag="
                    + audioPath);
        } else {
            ZToast.makeText(UserDkSubmitActivity.this, "音频不存在，请重新提交",
                    ZToast.LENGTH_SHORT).show();
        }
    }

    private final int CODE_REQUEST_RECORD_AUDIO_PERMISSION = 8801;


    @Override
    protected int setView() {
        return R.layout.activity_user_submit_dk;
    }

    /**
     * 上传图片uri集合
     */
    private List<String> uriList = new ArrayList<>();
    private KHBVideoPlayerStandard user_dk_video_submit;
    private ImageView submit_dk_avatar;
    private TextView submit_dk_username;
    private TextView user_dk_content;
    private KHBVideoPlayerStandard user_commit_video;
    private ImageView commit_dk_video_play;
    private GridView user_commit_grid;
    private LinearLayout user_commit_audios_layout;
    private ImageView user_commit_audios_img;
    private TextView user_commit_audios_text;
    private LinearLayout tea_comment_layout;
    private TextView teacher_dk_content;
    private LinearLayout teacher_dk_audios_layout;
    private ImageView teacher_commit_audios_img;
    private TextView teacher_commit_audios_text;
    private ImageView user_dk_audios_img_submit;
    private LinearLayout dk_result_submit;
    private FrameLayout r2_dub_video;
    private ImageView delete_video_view;
    private TextView user_dk_audios_text_submit;
    private ImageView user_submit_no;
    private LinearLayout user_dk_audios_submit_layout;
    private ImageView delete_audio_view;
    private TextView commit_dk_time;
    private ImageView submit_video_play;
    private ImageView user_dk_audio_img;
    private TeacherDKAdapter teacherDKAdapter;
    private ImageView user_dk_video_img;
    private DKAnswer dkAnswer;
    private Long dkTime;
    private GridView user_dk_grid_submit;
    private LinearLayout teacher_commit_lauout;
    private PeterTimeCountRefresh timer;

    private LinearLayout tj_user_dk_pictures_ll, tj_user_dk_video_ll, tj_user_dk_audio_ll;

    private String title;

    private String mWorkId;

    private ImageView user_dk_audios_img;


    private LinearLayout user_dk_audios_layout;

    private String audiosDuration;

    private TextView user_dk_audios_text;


    private TextView user_dk_workName;

    private TextView user_dk_workDetails;

    private List<String> picList;
    private GridView user_dk_grid;

    /**
     * 详情页图片适配器
     */
    private UserDKImgGridViewAdapter userDKImgGridViewAdapter;
    private DKWorkDays dkWorkDays;
    private ImageView dk_video_play;
    private ImageView user_dk_zk_img;
    private LinearLayout tj_user_submit_lay;
    private RelativeLayout user_dk_zk_lay;
    private ImageView img_micro_recording;
    private ImageView img_stop_recording;
    private List<String> subPicUri = new ArrayList<>();
    private int postion;
    private TextView dk_commit_date_text;
    private TextView dk_work_text;
    private LinearLayout dk_sub_lay;


    @Override
    protected void findViews() {

        Intent intent = getIntent();
        dkWorkDetail = (DkWorkDetail) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_DK_WORK_DETAIL);
        dkWorkDays = (DKWorkDays) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_DK_WORK_DAYS);
        postion = intent.getIntExtra(IntentFlag.INTENT_FLAG_POSITION, 0);
        dk_video_play = (ImageView) findViewById(R.id.tj_dk_video_play);
        user_dk_zk_img = (ImageView) findViewById(R.id.tj_user_dk_zk_img);
        mKHBVideoPlayerStandard = (KHBVideoPlayerStandard) findViewById(R.id.tj_user_dk_video);
        user_dk_grid = (GridView) findViewById(R.id.tj_user_dk_grid);
        user_dk_audios_img = (ImageView) findViewById(R.id.tj_user_dk_audios_img);
        user_dk_audios_layout = (LinearLayout) findViewById(R.id.tj_user_dk_audios_layout);
        user_dk_audios_text = (TextView) findViewById(R.id.tj_user_dk_audios_text);
        user_dk_workName = (TextView) findViewById(R.id.tj_user_dk_workName);
        user_dk_workDetails = (TextView) findViewById(R.id.tj_user_dk_workDetails);
        user_dk_audio_StateView = (PlayStateView) findViewById(R.id.tj_user_dk_audio_StateView);
        user_dk_audio_StateView_lay = (RelativeLayout) findViewById(R.id.tj_user_dk_audio_StateView_lay);
        user_dk_audio_complete = (TextView) findViewById(R.id.tj_user_dk_audio_complete);
        user_dk_edit_work = (EditText) findViewById(R.id.tj_user_dk_edit_work);
        user_dk_tex_editStatus = (TextView) findViewById(R.id.tj_user_dk_tex_editStatus);
        user_dk_pictures_img = (ImageView) findViewById(R.id.tj_user_dk_pictures_img);
        user_dk_video_submit = (KHBVideoPlayerStandard) findViewById(R.id.tj_user_dk_video_submit);
        user_commit_video = (KHBVideoPlayerStandard) findViewById(R.id.tj_user_commit_video);
        submit_video_play = (ImageView) findViewById(R.id.tj_submit_video_play);
        user_dk_submit = (RelativeLayout) findViewById(R.id.tj_user_dk_submit);
        user_dk_content = (TextView) findViewById(R.id.tj_user_dk_content);
        commit_dk_video_play = (ImageView) findViewById(R.id.tj_commit_dk_video_play);
        user_commit_grid = (GridView) findViewById(R.id.tj_user_commit_grid);
        user_commit_audios_layout = (LinearLayout) findViewById(R.id.tj_user_commit_audios_layout);
        user_commit_audios_img = (ImageView) findViewById(R.id.tj_user_commit_audios_img);
        user_commit_audios_text = (TextView) findViewById(R.id.tj_user_commit_audios_text);
        tea_comment_layout = (LinearLayout) findViewById(R.id.tj_tea_comment_layout);
        teacher_dk_content = (TextView) findViewById(R.id.tj_teacher_dk_content);
        teacher_dk_audios_layout = (LinearLayout) findViewById(R.id.tj_teacher_dk_audios_layout);
        teacher_commit_audios_img = (ImageView) findViewById(R.id.tj_teacher_commit_audios_img);
        teacher_commit_audios_text = (TextView) findViewById(R.id.tj_teacher_commit_audios_text);
        user_dk_zk_twxt = (TextView) findViewById(R.id.tj_user_dk_zk_twxt);
        dk_sub_lay = (LinearLayout) findViewById(R.id.dk_sub_lay);

        user_dk_audio_img = (ImageView) findViewById(R.id.tj_user_dk_audio_img);

        user_dk_grid_submit = (GridView) findViewById(R.id.tj_user_dk_grid_submit);
        user_dk_video_img = (ImageView) findViewById(R.id.tj_user_dk_video_img);

        teacher_commit_lauout = (LinearLayout) findViewById(R.id.tj_teacher_commit_lauout);
        submit_dk_avatar = (ImageView) findViewById(R.id.tj_submit_dk_avatar);
        submit_dk_username = (TextView) findViewById(R.id.tj_submit_dk_username);
        user_dk_audios_img_submit = (ImageView) findViewById(R.id.tj_user_dk_audios_img_submit);
        dk_result_submit = (LinearLayout) findViewById(R.id.tj_dk_result_submit);
        r2_dub_video = (FrameLayout) findViewById(R.id.tj_r2_dub_video);
        delete_video_view = (ImageView) findViewById(R.id.tj_delete_video_view);
        user_dk_audios_text_submit = (TextView) findViewById(R.id.tj_user_dk_audios_text_submit);
        //user_submit_no = (ImageView) findViewById(R.id.user_submit_no);
        user_dk_audios_submit_layout = (LinearLayout) findViewById(R.id.tj_user_dk_audios_submit_layout);
        delete_audio_view = (ImageView) findViewById(R.id.tj_delete_audio_view);
        tj_user_submit_lay = (LinearLayout) findViewById(R.id.tj_user_submit_lay);
        user_dk_zk_lay = (RelativeLayout) findViewById(R.id.tj_user_dk_zk_lay);
        img_micro_recording = findViewById(R.id.img_micro_recording);
        img_stop_recording = findViewById(R.id.img_stop_recording);
        dk_commit_date_text = findViewById(R.id.dk_commit_date_text);
        dk_work_text = findViewById(R.id.dk_work_text);
        tj_user_dk_pictures_ll = findViewById(R.id.tj_user_dk_pictures_ll);
        tj_user_dk_video_ll = findViewById(R.id.tj_user_dk_video_ll);
        tj_user_dk_audio_ll = findViewById(R.id.tj_user_dk_audio_ll);

        user_dk_audios_img_submit.setOnClickListener(this);
        user_dk_audios_submit_layout.setOnClickListener(this);
        img_stop_recording.setOnClickListener(this);
        dk_video_play.setOnClickListener(this);
        user_dk_zk_lay.setOnClickListener(this);
        submit_video_play.setOnClickListener(this);
        dk_result_submit.setOnClickListener(this);
        user_dk_audio_img.setOnClickListener(this);
        user_dk_pictures_img.setOnClickListener(this);
        user_dk_video_img.setOnClickListener(this);
        tj_user_dk_pictures_ll.setOnClickListener(this);
        tj_user_dk_video_ll.setOnClickListener(this);
        tj_user_dk_audio_ll.setOnClickListener(this);
        user_dk_audio_StateView.setOnClickListener(this);
        user_dk_audio_complete.setOnClickListener(this);
        user_commit_grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ArrayList<String> list = new ArrayList<>();
                list.addAll(subList);
                EpaperJumpManager.jumpToScanImage(UserDkSubmitActivity.this, R.string.go_back, list, i);
            }
        });
        user_dk_grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ArrayList<String> list = new ArrayList<>();
                list.addAll(picList);
                EpaperJumpManager.jumpToScanImage(UserDkSubmitActivity.this, R.string.go_back, list, i);
            }
        });

        user_dk_grid_submit.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ArrayList<String> list = new ArrayList<>();
                list.addAll(uriList);
                EpaperJumpManager.jumpToScanImage(UserDkSubmitActivity.this, R.string.go_back, list, i);
            }
        });

    }

    /**
     * 设置打卡作业view
     */
    private void setDKview() {

        if ("".equals(dkWorkDetail.getVedios()) || null == dkWorkDetail.getVedios()) {
            mKHBVideoPlayerStandard.setVisibility(View.GONE);
        } else {
            videoUri = dkWorkDetail.getVedios();
            mKHBVideoPlayerStandard.setVisibility(View.VISIBLE);
            initVideoView();
        }

        user_dk_edit_work.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                user_dk_tex_editStatus.setText(String.valueOf(s.length()) + "/1000");
                if (s.length() >= 1000) {
                    Toast.makeText(UserDkSubmitActivity.this, "上限了，亲", Toast.LENGTH_SHORT).show();
                }
            }
        });


        String dayText2 = "已进行" + (dkWorkDetail.getTodayDate().getDkDateNum() + 1) + "/" + dkWorkDetail.getDkdays() + "天";
        String dkDateNum = (dkWorkDetail.getTodayDate().getDkDateNum() + 1) + "";
        //ForegroundColorSpan 为文字前景色
        SpannableStringBuilder stringBuilder2 = new SpannableStringBuilder(dayText2);
        ForegroundColorSpan yellowSpan2 = new ForegroundColorSpan(Color.parseColor("#DE4A4A"));
        stringBuilder2.setSpan(yellowSpan2, 3, 3 + dkDateNum.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        dk_work_text.setText(stringBuilder2);


        if ("" == dkWorkDetail.getPictures() || null == dkWorkDetail.getPictures()) {
            user_dk_grid.setVisibility(View.GONE);
        } else {
            user_dk_grid.setVisibility(View.VISIBLE);
            picList = Arrays.asList(dkWorkDetail.getPictures().split(","));
            if ((null == videoUri || "".equals(videoUri)) && picList.size() > 2) {
                user_dk_grid.setNumColumns(3);
            } else {
                user_dk_grid.setNumColumns(2);
            }
            userDKImgGridViewAdapter = new UserDKImgGridViewAdapter(UserDkSubmitActivity.this, picList, dkWorkDetail.getVedios());
            user_dk_grid.setAdapter(userDKImgGridViewAdapter);
        }


        title = dkWorkDetail.getWorkName();
        long dkDate = dkWorkDays.getDkDate();
        long date = dkDate * 1000;
        setTitleText(CWUtils.formatDate6(date) + "  " + title);

        if (null != dkWorkDetail.getWorkName()) {
            user_dk_workName.setText(dkWorkDetail.getWorkName());
        }
        if (null != dkWorkDetail.getWorkDetails()) {
            user_dk_workDetails.setText(dkWorkDetail.getWorkDetails());
        }

        if ("".equals(dkWorkDetail.getAudios()) || null == dkWorkDetail.getAudios()) {
            user_dk_audios_layout.setVisibility(View.GONE);
        } else {
            //获取音频时长
            String duration = getDuration(dkWorkDetail.getAudios());

            user_dk_audios_text.setText(duration);
            user_dk_audios_layout.setVisibility(View.VISIBLE);

            user_dk_audios_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // AudioPlayer.getInstance().play(dkWorkDetail.getAudios(),null);
                    try {
                        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                            Log.e("MediaPlayer ", "停止播放");
                            Drawable drawable = user_commit_audios_img.getDrawable();
                            Drawable drawable2 = teacher_commit_audios_img.getDrawable();
                            Drawable drawable3 = user_dk_audios_img_submit.getDrawable();
                            if (drawable != null && drawable instanceof AnimationDrawable) {
                                stopPlayAnimation(user_commit_audios_img);
                                timer.cancel();
                                mediaPlayer.stop();
                                mediaPlayer.release();
                                mediaPlayer = null;
                                startPlayAnimation(user_dk_audios_img);
                                getDurationLong(dkWorkDetail.getAudios());
                                timer = new PeterTimeCountRefresh((long) durationLong, 1000, user_dk_audios_text);
                                timer.start();
                                mediaPlayer = new MediaPlayer();
                                mediaPlayer.setDataSource(dkWorkDetail.getAudios());
                                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                                mediaPlayer.prepareAsync();
                                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                                    @Override
                                    public void onPrepared(MediaPlayer mp) {
                                        Log.e("MediaPlayer ", "开始播放");
                                        mediaPlayer.start();
                                    }
                                });
                                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                    @Override
                                    public void onCompletion(MediaPlayer mediaPlayer) {
                                        Log.e("MediaPlayer ", "停止播放");
                                        stopPlayAnimation(user_dk_audios_img);
                                    }
                                });
                            } else if (drawable2 != null && drawable2 instanceof AnimationDrawable) {
                                stopPlayAnimation(teacher_commit_audios_img);
                                timer.cancel();
                                mediaPlayer.stop();
                                mediaPlayer.release();
                                mediaPlayer = null;
                                startPlayAnimation(user_dk_audios_img);
                                getDurationLong(dkWorkDetail.getAudios());
                                timer = new PeterTimeCountRefresh((long) durationLong, 1000, user_dk_audios_text);
                                timer.start();
                                mediaPlayer = new MediaPlayer();
                                mediaPlayer.setDataSource(dkWorkDetail.getAudios());
                                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                                mediaPlayer.prepareAsync();
                                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                                    @Override
                                    public void onPrepared(MediaPlayer mp) {
                                        Log.e("MediaPlayer ", "开始播放");
                                        mediaPlayer.start();
                                    }
                                });
                                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                    @Override
                                    public void onCompletion(MediaPlayer mediaPlayer) {
                                        Log.e("MediaPlayer ", "停止播放");
                                        stopPlayAnimation(user_dk_audios_img);
                                    }
                                });

                            } else if (drawable3 != null && drawable3 instanceof AnimationDrawable) {
                                stopPlayAnimation(user_dk_audios_img_submit);
                                timer.cancel();
                                mediaPlayer.stop();
                                mediaPlayer.release();
                                mediaPlayer = null;
                                startPlayAnimation(user_dk_audios_img);
                                getDurationLong(dkWorkDetail.getAudios());
                                timer = new PeterTimeCountRefresh((long) durationLong, 1000, user_dk_audios_text);
                                timer.start();
                                mediaPlayer = new MediaPlayer();
                                mediaPlayer.setDataSource(dkWorkDetail.getAudios());
                                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                                mediaPlayer.prepareAsync();
                                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                                    @Override
                                    public void onPrepared(MediaPlayer mp) {
                                        Log.e("MediaPlayer ", "开始播放");
                                        mediaPlayer.start();
                                    }
                                });
                                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                    @Override
                                    public void onCompletion(MediaPlayer mediaPlayer) {
                                        Log.e("MediaPlayer ", "停止播放");
                                        stopPlayAnimation(user_dk_audios_img);
                                    }
                                });

                            } else {
                                stopPlayAnimation(user_dk_audios_img);
                                timer.cancel();
                                mediaPlayer.stop();
                                mediaPlayer.release();
                                mediaPlayer = null;
                            }

                        } else {

                            startPlayAnimation(user_dk_audios_img); // 开始线程，更新进度条的刻度
                            /*handler.postDelayed(startRunnable, 500);
                            // 开始线程，停止播放
                            handler.postDelayed(stopRunnable,
                                     300);*/
                            getDurationLong(dkWorkDetail.getAudios());
                            timer = new PeterTimeCountRefresh((long) durationLong, 1000, user_dk_audios_text);
                            timer.start();
                            mediaPlayer = new MediaPlayer();
                            mediaPlayer.setDataSource(dkWorkDetail.getAudios());
                            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                            mediaPlayer.prepareAsync();
                            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                                @Override
                                public void onPrepared(MediaPlayer mp) {
                                    Log.e("MediaPlayer ", "开始播放");
                                    mediaPlayer.start();
                                }
                            });
                            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                @Override
                                public void onCompletion(MediaPlayer mediaPlayer) {
                                    Log.e("MediaPlayer ", "停止播放");
                                    stopPlayAnimation(user_dk_audios_img);
                                }
                            });
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            });
        }
    }

    /**
     * 设置打卡作业信息
     *
     * @param dkWorkDays
     */
    public void setUserInfo(DKWorkDays dkWorkDays) {
        if (dkWorkDays.getIsDk() == 1) {
            final DoDKWorkInfo doDKWorkInfo = dkWorkDays.getDoDkWorkInfo();
            dk_result_submit.setVisibility(View.GONE);
            if (null != doDKWorkInfo) {
                if (null != doDKWorkInfo.getVedios() && !"".equals(doDKWorkInfo.getVedios())) {
                    user_commit_video.setVisibility(View.VISIBLE);
                    String localVideoPath = ESystem.getDubingVideoPath() + File.separator + StringUtils.md5(doDKWorkInfo.getVedios());
                    File commitFile = new File(localVideoPath);
                    if (commitFile.exists()) {
                        user_commit_video.setplsyModeUrlUp(localVideoPath, KHBVideoPlayer.SCREEN_LAYOUT_LIST, KHBVideoPlayer.PLAY_MODE_UNMUTE, "");
                    } else {
                        user_commit_video.setplsyModeUrlUp(doDKWorkInfo.getVedios(), KHBVideoPlayer.SCREEN_LAYOUT_LIST, KHBVideoPlayer.PLAY_MODE_UNMUTE, "");
                        downWork(doDKWorkInfo.getVedios(), localVideoPath);
                    }

                } else {
                    user_commit_video.setVisibility(View.GONE);
                }

                if (null != doDKWorkInfo.getPictures() && !"".equals(doDKWorkInfo.getPictures())) {
                    user_commit_grid.setVisibility(View.VISIBLE);
                    subList = Arrays.asList(doDKWorkInfo.getPictures().split(","));
                    if ((null == doDKWorkInfo.getVedios() || "".equals(doDKWorkInfo.getVedios())) && subList.size() > 1) {
                        user_commit_grid.setNumColumns(3);
                    } else {
                        user_commit_grid.setNumColumns(2);
                    }
                    teacherDKAdapter = new TeacherDKAdapter(UserDkSubmitActivity.this, subList, doDKWorkInfo.getVedios());
                    user_commit_grid.setAdapter(teacherDKAdapter);
                } else {
                    user_commit_grid.setVisibility(View.GONE);
                }
                long dkDate = doDKWorkInfo.getSubmitDate();
                dk_commit_date_text.setText(CWUtils.convertDKTime(dkDate * 1000));

                if (null != doDKWorkInfo.getAudios() && !"".equals(doDKWorkInfo.getAudios())) {
                    //获取音频时长
                    durationStr = getDuration(doDKWorkInfo.getAudios());
                    durationAudios = doDKWorkInfo.getAudios();
                    user_commit_audios_text.setText(durationStr);
                    user_commit_audios_layout.setVisibility(View.VISIBLE);
                    user_commit_audios_layout.setOnClickListener(mediaSubmitListener);
                    user_commit_audios_img.setOnClickListener(mediaSubmitListener);

                } else {
                    user_commit_audios_layout.setVisibility(View.GONE);
                }

                if (null == doDKWorkInfo.getComment() || "".equals(doDKWorkInfo.getComment())) {
                    tea_comment_layout.setVisibility(View.GONE);
                } else {
                    tea_comment_layout.setVisibility(View.VISIBLE);
                    if (doDKWorkInfo.getCommentType().equals("1")) {
                        teacher_dk_audios_layout.setVisibility(View.GONE);
                        teacher_dk_content.setText(dkWorkDetail.getPublishUserName() + ":" + doDKWorkInfo.getComment());
                    } else if (doDKWorkInfo.getCommentType().equals("2")) {
                        teacher_dk_content.setText(dkWorkDetail.getPublishUserName() + ":");
                        teacher_dk_audios_layout.setVisibility(View.VISIBLE);
                        //获取音频时长
                        durationStr = getDuration(doDKWorkInfo.getComment());
                        durationAudios = doDKWorkInfo.getComment();
                        teacher_commit_audios_text.setText(durationStr);
                        teacher_dk_audios_layout.setOnClickListener(mediaPlayerListener);
                        teacher_commit_audios_img.setOnClickListener(mediaPlayerListener);
                    }
                }

                submit_dk_username.setText(doDKWorkInfo.getUserName());
                if (null != doDKWorkInfo.getContent() && !"".equals(doDKWorkInfo.getContent())) {
                    user_dk_content.setText(doDKWorkInfo.getContent());
                    user_dk_content.setVisibility(View.VISIBLE);
                } else {
                    user_dk_content.setVisibility(View.GONE);
                }

            }
            UserInfoBase userInfo = getUserInfoBase();
            if (userInfo != null) {
                String avatar = userInfo.getAvatar();
                avatar = TextUtils.isEmpty(avatar) ? getString(R.string.default_avatar_file_path) + R.mipmap.head : avatar;
                try {
                    ImageLoader.getInstance().displayImage(avatar, submit_dk_avatar, EConstants.getDefAvatarCircleBuilder());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // commit_dk_time.setText(CWUtils.getWorkTime(dkTime));
            tj_user_submit_lay.setVisibility(View.GONE);
            teacher_commit_lauout.setVisibility(View.VISIBLE);
        } else if (dkWorkDays.getIsDk() == 0 && dkWorkDetail.getTodayDate().getDkDateNum() == dkWorkDays.getDkDateNum()) {
            user_dk_audio_StateView.setUnAutoRecordState(true);
            dk_result_submit.setVisibility(View.VISIBLE);
            teacher_commit_lauout.setVisibility(View.GONE);
            tj_user_submit_lay.setVisibility(View.VISIBLE);
        }
    }

    private View.OnClickListener mediaSubmitListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // AudioPlayer.getInstance().play(dkWorkDetail.getAudios(),null);
            try {
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    Log.e("MediaPlayer ", "停止播放");
                    Drawable drawable = user_dk_audios_img.getDrawable();
                    if (drawable != null && drawable instanceof AnimationDrawable) {
                        stopPlayAnimation(user_dk_audios_img);
                        timer.cancel();
                        mediaPlayer.stop();
                        mediaPlayer.release();
                        mediaPlayer = null;
                        startPlayAnimation(user_commit_audios_img);
                        //Uri uu = FileProvider7.getUriForFile(this, audioFile);
                        getDurationLong(durationAudios);
                        timer = new PeterTimeCountRefresh((long) durationLong, 1000, user_commit_audios_text);
                        timer.start();
                        mediaPlayer = new MediaPlayer();
                        mediaPlayer.setDataSource(durationAudios);
                        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                        mediaPlayer.prepareAsync();
                        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                            @Override
                            public void onPrepared(MediaPlayer mp) {
                                Log.e("MediaPlayer ", "开始播放");
                                mediaPlayer.start();
                            }
                        });
                        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mediaPlayer) {
                                Log.e("MediaPlayer ", "停止播放");
                                stopPlayAnimation(user_commit_audios_img);
                            }
                        });
                    } else {
                        stopPlayAnimation(user_commit_audios_img);
                        timer.cancel();
                        mediaPlayer.stop();
                        mediaPlayer.release();
                        mediaPlayer = null;
                    }

                } else {
                    startPlayAnimation(user_commit_audios_img); // 开始线程，更新进度条的刻度
                            /*handler.postDelayed(startRunnable, 500);
                            // 开始线程，停止播放
                            handler.postDelayed(stopRunnable,
                                     300);*/
                    getDurationLong(durationAudios);
                    timer = new PeterTimeCountRefresh((long) durationLong, 1000, user_commit_audios_text);
                    timer.start();
                    mediaPlayer = new MediaPlayer();
                    mediaPlayer.setDataSource(durationAudios);
                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    mediaPlayer.prepareAsync();
                    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            Log.e("MediaPlayer ", "开始播放");
                            mediaPlayer.start();
                        }
                    });
                    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mediaPlayer) {
                            Log.e("MediaPlayer ", "停止播放");
                            stopPlayAnimation(user_commit_audios_img);
                        }
                    });
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    };

    private View.OnClickListener mediaPlayerListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // AudioPlayer.getInstance().play(dkWorkDetail.getAudios(),null);
            try {
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    Log.e("MediaPlayer ", "停止播放");
                    Drawable drawable = user_dk_audios_img.getDrawable();
                    if (drawable != null && drawable instanceof AnimationDrawable) {
                        stopPlayAnimation(user_dk_audios_img);
                        timer.cancel();
                        mediaPlayer.stop();
                        mediaPlayer.release();
                        mediaPlayer = null;
                        getDurationLong(durationAudios);
                        timer = new PeterTimeCountRefresh((long) durationLong, 1000, teacher_commit_audios_text);
                        timer.start();
                        startPlayAnimation(teacher_commit_audios_img); // 开始线程，更新进度条的刻度
                            /*handler.postDelayed(startRunnable, 500);
                            // 开始线程，停止播放
                            handler.postDelayed(stopRunnable,
                                     300);*/
                        mediaPlayer = new MediaPlayer();
                        mediaPlayer.setDataSource(durationAudios);
                        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                        mediaPlayer.prepareAsync();
                        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                            @Override
                            public void onPrepared(MediaPlayer mp) {
                                Log.e("MediaPlayer ", "开始播放");
                                mediaPlayer.start();
                            }
                        });
                        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mediaPlayer) {
                                Log.e("MediaPlayer ", "停止播放");
                                stopPlayAnimation(teacher_commit_audios_img);
                            }
                        });
                    } else {
                        stopPlayAnimation(teacher_commit_audios_img);
                        timer.cancel();
                        mediaPlayer.stop();
                        mediaPlayer.release();
                        mediaPlayer = null;
                    }

                } else {
                    getDurationLong(durationAudios);
                    timer = new PeterTimeCountRefresh((long) durationLong, 1000, teacher_commit_audios_text);
                    timer.start();
                    startPlayAnimation(teacher_commit_audios_img); // 开始线程，更新进度条的刻度
                            /*handler.postDelayed(startRunnable, 500);
                            // 开始线程，停止播放
                            handler.postDelayed(stopRunnable,
                                     300);*/
                    mediaPlayer = new MediaPlayer();
                    mediaPlayer.setDataSource(durationAudios);
                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    mediaPlayer.prepareAsync();
                    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            Log.e("MediaPlayer ", "开始播放");
                            mediaPlayer.start();
                        }
                    });
                    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mediaPlayer) {
                            Log.e("MediaPlayer ", "停止播放");
                            stopPlayAnimation(teacher_commit_audios_img);
                        }
                    });
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    };
    @Override
    protected void initEvent() {
        initVideoView();
    }

    @Override
    protected void init() {
        setValideSource(false);
        setBottomMenuDialog();
        //setCwDialog();
        ALiYunManager.getInstance().registerListener(aLiYunListener);
    }


    public void setImageView(List<String> list) {
        if (list.size() > 0) {
            user_dk_grid_submit.setVisibility(View.VISIBLE);
            user_dk_pictures_img.setImageResource(R.drawable.user_dk_pictures_img);
            user_dk_pictures_img.setOnClickListener(UserDkSubmitActivity.this);
        } else {
            user_dk_grid_submit.setVisibility(View.GONE);
            user_dk_pictures_img.setImageResource(R.drawable.user_dk_pictures_img);
            user_dk_pictures_img.setOnClickListener(UserDkSubmitActivity.this);
        }
    }


    public void getUserDkWorkDetails(String workId) {
        EpaperDao.getInstance().getUserDkWorkDetails(workId, new BaseExtCallBack(UserDkSubmitActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(int errorCode, Object data) {
                hideCricleProgress();
                super.failed(errorCode, data);
                failed(data);

            }

            @Override
            public void failed(Object data) {
                if (data instanceof TimeoutError) {
                    hideCricleProgress();
                    ToastUtil.INSTANCE.toastCenterError("加载失败，检查网络重新请求");
                }

            }


            @Override
            public void success(Object data) {
                hideCricleProgress();
                if (null != data) {
                    DkWorkDetail newDkWorkDetail = (DkWorkDetail) data;
                    DKWorkDays newDKWorkDays = newDkWorkDetail.getDkworkdays().get(UserDkSubmitActivity.this.dkWorkDays.getDkDateNum());
                    setUserInfo(newDKWorkDays);
                    subVideoPath = "";
                    audioPath = "";
                    subPicList.clear();
                    editText = "";
                }
            }
        });
    }

    @Override
    protected void loadData() {
        if (null != dkWorkDetail && null != dkWorkDays) {
            setDKview();
            setUserInfo(dkWorkDays);
        }

        //  showCricleProgress();

    }

    /*private void setCwDialog(){
        cwDialog = new CWDialog(this);
        cwDialog.setCustomDialog(R.layout.activity_dk_audio);
    }*/

    private void setBottomMenuDialog() {
        bottomMenuDialog = new BottomMenuDialog(this);
        bottomMenuDialog
                .setBtnTextColor(getResources().getColor(R.color.color_light_green));
        bottomMenuDialog
                .setLastBtnTextColor(getResources().getColor(R.color.gray));

        ArrayList<String> str = new ArrayList<>();
        if (videoOrPhoto == 1) {
            str.add(getResources().getString(R.string.avatar_camera));
            str.add(getResources().getString(R.string.avatar_photo));
        } else {
            str.add(getResources().getString(R.string.avatar_video));
            str.add(getResources().getString(R.string.avatar_local_video));
        }

        str.add(getResources().getString(android.R.string.cancel));
        bottomMenuDialog.setMenuTextList(str);

        ArrayList<View.OnClickListener> listeners = new ArrayList<>();

        listeners.add(new BottomClickListener(0));
        listeners.add(new BottomClickListener(1));
        listeners.add(new BottomClickListener(2));

        bottomMenuDialog.setMenuOnClickListeners(listeners);
    }


    class BottomClickListener extends ViewOnClickListener {
        private int index;

        public BottomClickListener(int index) {
            this.index = index;
        }

        @Override
        public void avertRepeatOnClick(View v) {
            switch (index) {
                case 0:// 拍照
                    showgetCameraPermissDialog();
                    break;
                case 1:// 从相册选
                    showgetAlbumPermissDialog();
                    break;
                default:
                    break;
            }
            bottomMenuDialog.dismiss();
        }
    }

    private final int CODE_REQUEST_ALBUM_PERMISSION = 9900;
    private final int CODE_REQUEST_CAMERA_PERMISSION = 9901;
    private CWDialog getAlbumPermissDialog;

    /**
     * 获取Album权限提示框
     */
    private boolean showgetAlbumPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            useAlbum();
        } else {
            if (getAlbumPermissDialog == null) {
                getAlbumPermissDialog = new CWDialog(this);
                getAlbumPermissDialog.setTitle(R.string.get_permiss_title);
                getAlbumPermissDialog.setTitleTextColor(Color.BLACK);
                getAlbumPermissDialog.setMessage(getString(R.string.get_album_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getAlbumPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getAlbumPermissDialog.dismiss();
                        useAlbum();
                    }
                });
                getAlbumPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getAlbumPermissDialog.dismiss();
                    }
                });
            }
            getAlbumPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用相册，判断权限
     */
    private void useAlbum() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读取相册权限");
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_ALBUM_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                if (videoOrPhoto == 1) {
                                    BaseJumpManager.jumpToChoosePic(UserDkSubmitActivity.this, (9 - uriList.size()),
                                            REQUEST_CODE_ALBUM);
                                } else {
                                    BaseJumpManager.jumpToSysChooseVideoFile(UserDkSubmitActivity.this, REQUEST_VIDEO_CODE);
                                }

                            } else {
//                                showConfirmCommitDialog(MyInfoActivity, "未获取到读取相册权限，无法正常使用相册。");
                            }
                        }
                    });
        } else {
            BaseJumpManager.jumpToChoosePic(UserDkSubmitActivity.this, (9 - uriList.size()),
                    REQUEST_CODE_ALBUM);
        }
    }

    private CWDialog getCameraPermissDialog;

    /**
     * 获取Camera权限提示框
     */
    private boolean showgetCameraPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.CAMERA);
        if (Build.VERSION.SDK_INT < 23 || isHavePermiss) {
            useCamera();
        } else {
            if (getCameraPermissDialog == null) {
                getCameraPermissDialog = new CWDialog(this);
                getCameraPermissDialog.setTitle(R.string.get_permiss_title);
                getCameraPermissDialog.setTitleTextColor(Color.BLACK);
                getCameraPermissDialog.setMessage(getString(R.string.get_camera_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getCameraPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getCameraPermissDialog.dismiss();
                        useCamera();
                    }
                });
                getCameraPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getCameraPermissDialog.dismiss();
                    }
                });
            }
            getCameraPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用照相机，判断权限
     */
    private void useCamera() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList_camera = new ArrayList<String>();
            Map<String, String> noteMap_camera = new HashMap<>();
            noteMap_camera.put(Manifest.permission.CAMERA, "相机权限");
            permissionList_camera.add(Manifest.permission.CAMERA);
//            if (Build.VERSION.SDK_INT >= 30) {
//                permissionList_camera.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
//                noteMap_camera.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读取相册权限");
//            }
            XXPermissionTool.checkPermissions(this, //
                    permissionList_camera, //
                    noteMap_camera, //
                    CODE_REQUEST_CAMERA_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                if (videoOrPhoto == 1) {
                                    tempFile = ESystem.getPicturesCacheDir(UserDkSubmitActivity.this, ESystem.getCacheFileName("dkWork", "jpg"));
                                    BaseJumpManager.jumpToSysCamera(UserDkSubmitActivity.this,
                                            tempFile, REQUEST_CODE_CAMERA);
                                } else {
                                    BaseJumpManager.jumpToVideo(UserDkSubmitActivity.this, videoFile, ACTION_VIDEO_CAPTURE);
                                }

                            } else {
//                                showConfirmCommitDialog(MyInfoActivity.this, "未获取到使用相机权限，无法正常使用照相机。");
                            }
                        }
                    });
        } else {
            tempFile = ESystem.getPicturesCacheDir(UserDkSubmitActivity.this, ViewUtil.getPhotoFileName());
            BaseJumpManager.jumpToSysCamera(UserDkSubmitActivity.this,
                    tempFile, REQUEST_CODE_CAMERA);
        }
    }

    /**
     * 开始播放动画
     */
    private void startPlayAnimation(ImageView imageView) {
        imageView
                .setImageResource(R.drawable.dk_bg_annimation);

        final AnimationDrawable animationDrawable = (AnimationDrawable) imageView
                .getDrawable();
        animationDrawable.start();
    }

    /**
     * 停止播放动画
     */
    private void stopPlayAnimation(ImageView imageView) {
        Drawable drawable = imageView.getDrawable();
        if (drawable != null && drawable instanceof AnimationDrawable) {
            ((AnimationDrawable) drawable).stop();
        }
        imageView.setImageResource(R.mipmap.dk_icon_sound_3);
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tj_dk_video_play) {
            mKHBVideoPlayerStandard.startVideo(KHBVideoPlayer.PLAY_MODE_UNMUTE);
        } else if (id == R.id.tj_user_dk_pictures_img || id == R.id.tj_user_dk_pictures_ll) {
            videoOrPhoto = 1;
            setBottomMenuDialog();
            bottomMenuDialog.show();
            /*if(uriList.size() == 9){

            }else {
                bottomMenuDialog.show();
            }*/
        } else if (id == R.id.tj_user_dk_zk_lay) {
            if (isZkOrSq) {
                isZkOrSq = false;
                user_dk_workDetails.setVisibility(View.GONE);
                user_dk_zk_twxt.setText("展开");
                user_dk_zk_img.setImageDrawable(this.getResources().getDrawable(R.drawable.user_dk_zk));
            } else {
                isZkOrSq = true;
                user_dk_workDetails.setVisibility(View.VISIBLE);
                user_dk_zk_twxt.setText("收起");
                user_dk_zk_img.setImageDrawable(this.getResources().getDrawable(R.drawable.user_dk_sq));
            }
        } else if (id == R.id.tj_user_dk_audio_complete) {
            audioPath = "";
            stopRecord();
            handler.removeCallbacks(stopRecordRunnable);
            user_dk_audio_StateView_lay.setVisibility(View.GONE);
            //dk_result_submit.setVisibility(View.VISIBLE);
            //cwDialog.dismiss();
        } else if (id == R.id.tj_submit_video_play) {
            user_dk_video_submit.startVideo(KHBVideoPlayer.PLAY_MODE_UNMUTE);
            user_dk_video_submit.startWindowFullscreen();
        } else if (id == R.id.tj_user_dk_audio_img || id == R.id.tj_user_dk_audio_ll) {
            user_dk_audio_StateView_lay.setVisibility(View.VISIBLE);
            //cwDialog.show();
            user_dk_audio_StateView.setDKAutoRecordState(true);
            //dk_result_submit.setVisibility(View.GONE);
        } else if (id == R.id.tj_user_dk_audio_StateView) {
            showgetRecordPermissDialog();
        } else if (id == R.id.img_stop_recording) {
            stopRecord();
        } else if (id == R.id.tj_user_dk_video_img || id == R.id.tj_user_dk_video_ll) {
            videoOrPhoto = 2;
            setBottomMenuDialog();
            bottomMenuDialog.show();
        } else if (id == R.id.tj_commit_dk_video_play) {
            user_commit_video.startVideo(KHBVideoPlayer.PLAY_MODE_UNMUTE);
            user_commit_video.startWindowFullscreen();
        } else if (id == R.id.tj_user_dk_audios_img_submit || id == R.id.tj_user_dk_audios_submit_layout) {
            // AudioPlayer.getInstance().play(dkWorkDetail.getAudios(),null);
            try {
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    Log.e("MediaPlayer ", "停止播放");
                    Drawable drawable = user_dk_audios_img.getDrawable();
                    if (drawable != null && drawable instanceof AnimationDrawable) {
                        stopPlayAnimation(user_dk_audios_img);
                        timer.cancel();
                        mediaPlayer.stop();
                        mediaPlayer.release();
                        mediaPlayer = null;
                        startPlayAnimation(user_dk_audios_img_submit);
                        mediaPlayer = new MediaPlayer();
                        //Uri uu = FileProvider7.getUriForFile(this, audioFile);
                        getDurationLong(audioPath);
                        timer = new PeterTimeCountRefresh((long) durationLong, 1000, user_dk_audios_text_submit);
                        timer.start();
                        mediaPlayer.setDataSource(audioPath);
                        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                        mediaPlayer.prepareAsync();
                        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                            @Override
                            public void onPrepared(MediaPlayer mp) {
                                Log.e("MediaPlayer ", "开始播放");
                                mediaPlayer.start();
                            }
                        });
                        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mediaPlayer) {
                                Log.e("MediaPlayer ", "停止播放");
                                stopPlayAnimation(user_dk_audios_img_submit);
                            }
                        });
                    } else {
                        stopPlayAnimation(user_dk_audios_img_submit);
                        //user_dk_audios_img.setImageResource(R.mipmap.dk_icon_sound_3);
                        timer.cancel();
                        mediaPlayer.stop();
                        mediaPlayer.release();
                        mediaPlayer = null;
                    }

                } else {
                    startPlayAnimation(user_dk_audios_img_submit); // 开始线程，更新进度条的刻度
                            /*handler.postDelayed(startRunnable, 500);
                            // 开始线程，停止播放
                            handler.postDelayed(stopRunnable,
                                     300);*/
                    mediaPlayer = new MediaPlayer();
                    //Uri uu = FileProvider7.getUriForFile(this, audioFile);
                    getDurationLong(audioPath);
                    timer = new PeterTimeCountRefresh((long) durationLong, 1000, user_dk_audios_text_submit);
                    timer.start();
                    mediaPlayer.setDataSource(audioPath);
                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    mediaPlayer.prepareAsync();
                    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            Log.e("MediaPlayer ", "开始播放");
                            mediaPlayer.start();
                        }
                    });
                    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mediaPlayer) {
                            Log.e("MediaPlayer ", "停止播放");
                            stopPlayAnimation(user_dk_audios_img_submit);
                        }
                    });
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (id == R.id.tj_dk_result_submit) {
            String editText = user_dk_edit_work.getText().toString();
            if (null != subVideoPath || null != audioPath || subPicList.size() != 0 || !"".equals(editText)) {
                if (!"".equals(subVideoPath) && null != subVideoPath) {
                    videoCount = 1;
                    submitVideo();

                }
                if (!"".equals(audioPath) && null != audioPath) {
                    audioCount = 1;
                    addResult();
                }

                if (subPicList.size() != 0 && null != subPicList) {
                    picCount = subPicList.size();
                    for (int i = 0; i < subPicList.size(); i++) {
                        submitPic(subPicList.get(i));
                    }
                }

                if ((null == subVideoPath || "".equals(subVideoPath)) && (null == audioPath || "".equals(audioPath)) && subPicList.size() == 0 && !"".equals(editText)) {
                    showCricleProgress("正在提交中，请稍等");
                    submitDK();
                }


            } else {
                ToastUtil.INSTANCE.toastCenterError("请上传内容后再提交");
            }
        }


    }


    private Handler mRecorderHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (isFinishing()) {
                return;
            }
            switch (msg.what) {
                case Mp3Recorder.MSG_REC_STARTED:// 录音开始
                    /*img_micro_recording.setVisibility(View.VISIBLE);
                    Drawable drawable = img_micro_recording.getDrawable();
                    if (drawable != null && drawable instanceof AnimationDrawable) {
                        ((AnimationDrawable) drawable).start();
                    }
*/
                    break;
                case Mp3Recorder.MSG_DB:// 录音分贝
                    Bundle b = msg.getData();
//                    Log.d(TAG, "###########Mp3Recorder.MSG_DB############" + Mp3Recorder.MSG_DB);
                    if (b != null) {
                        double db = b.getDouble("db");
                        if (db >= 0) {
                            Log.d(TAG, "###########db############" + db);
                            mVolume = db;
                        }
//                        Log.d(TAG, "###########db############" + db);

//                        if (microRecording != null && !Double.isNaN(db)) {
//                            microRecording.setRms(db);
//                        }
                    }
                    break;
                case Mp3Recorder.MSG_ERROR_AUDIO_RECORD:// 录音失败
                    isRecordFail = true;
                    Log.d(TAG, "###########Mp3Recorder.MSG_ERROR_AUDIO_RECORD############" + Mp3Recorder.MSG_ERROR_AUDIO_RECORD);
                    DialogUtil.showSettingPermissions(UserDkSubmitActivity.this);
                    break;

                case Mp3Recorder.MSG_ERROR_REC_START:
                    isRecordFail = true;
                    Log.d(TAG, "###########Mp3Recorder.MSG_ERROR_REC_START############" + Mp3Recorder.MSG_ERROR_AUDIO_RECORD);

                    DialogUtil.showSettingPermissions(UserDkSubmitActivity.this);
                    break;
                case Mp3Recorder.MSG_REC_STOPPED:// 录音结束
                    /*img_micro_recording.setVisibility(View.GONE);
                    Drawable drawable2 = img_micro_recording.getDrawable();
                    if (drawable2 != null && drawable2 instanceof AnimationDrawable) {
                        ((AnimationDrawable) drawable2).stop();
                    }*/
                    break;
                default:
                    break;
            }
        }

    };


    public void startRecord() {

        audioPath = ESystem.getAudioRecordPath(UserDkSubmitActivity.this) + File.separator + getAudioFileName();
        mp3Recorder = new Mp3Recorder(audioPath, BaseConstants.SAMPLERATE, mRecorderHandler);
        mp3Recorder.start();

    }

    public static boolean isGrantExternalRW(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && activity.checkSelfPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            activity.requestPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, 1);

            return false;
        }

        return true;
    }

    /**
     * 获取音频时长
     *
     * @param audios
     * @return
     */
    private String getDuration(String audios) {
        MediaPlayer mediaPlayer = new MediaPlayer();
        String audiosDuration = "";
        try {
            mediaPlayer.setDataSource(audios);
            mediaPlayer.prepare();
            int duration = mediaPlayer.getDuration();
            if (0 != duration) {
                audiosDuration = formatTime(duration);
                //释放资源
                mediaPlayer.release();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return audiosDuration;
    }


    /**
     * 获取音频时长
     *
     * @param audios
     * @return
     */
    private int getDurationLong(String audios) {
        MediaPlayer mediaPlayer = new MediaPlayer();
        String audiosDuration = "";
        try {
            mediaPlayer.setDataSource(audios);
            mediaPlayer.prepare();
            durationLong = mediaPlayer.getDuration();
            if (0 != durationLong) {
                //audiosDuration = formatTime(duration);
                //释放资源
                mediaPlayer.release();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return durationLong;
    }

    /**
     * 格式化音频时长
     *
     * @param timeTemp
     * @return
     */
    public static String formatTime(Object timeTemp) {
        int timeParam = 0;
        if (timeTemp instanceof Integer) {
            timeParam = (Integer) timeTemp / 1000;
        }
        if (timeTemp instanceof String) {
            timeParam = Integer.valueOf((String) timeTemp);
        }

        int second = timeParam % 60;
        int minuteTemp = timeParam / 60;
        if (minuteTemp > 0) {
            int minute = minuteTemp % 60;
            int hour = minuteTemp / 60;
            if (hour > 0) {
                return (hour > 10 ? (hour + "") : ("0" + hour)) + ":" + (minute > 10 ? (minute + "") : ("0" + minute))
                        + ":" + (second > 10 ? (second + "") : ("0" + second));
            } else {
                return (minute > 10 ? (minute + "") : ("0" + minute)) + ":"
                        + (second > 10 ? (second + "") : ("0" + second));
            }
        } else {
            return "00:" + (second > 10 ? (second + "") : ("0" + second));
        }
    }

    private CWDialog getRecordPermissDialog;

    /**
     * 获取Record权限提示框
     */
    private boolean showgetRecordPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.RECORD_AUDIO);
        if (isHavePermiss) {
            checkRecordAudioPermiss();
        } else {
            if (getRecordPermissDialog == null) {
                getRecordPermissDialog = new CWDialog(this);
                getRecordPermissDialog.setTitle(R.string.get_permiss_title);
                getRecordPermissDialog.setTitleTextColor(Color.BLACK);
                getRecordPermissDialog.setMessage(getString(R.string.get_record_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getRecordPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getRecordPermissDialog.dismiss();
                        checkRecordAudioPermiss();
                    }
                });
                getRecordPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getRecordPermissDialog.dismiss();
                    }
                });
            }
            getRecordPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用录音，判断权限
     */
    private boolean checkRecordAudioPermiss() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.RECORD_AUDIO);
            noteMap.put(Manifest.permission.RECORD_AUDIO, "录音权限");
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_RECORD_AUDIO_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                record();
                            }
                        }
                    });
        } else {
            record();
        }
        return true;
    }

    private Handler handler = new Handler(Looper.getMainLooper());

    private Runnable stopRecordRunnable = new Runnable() {
        public void run() {
            stopRecord();
        }
    };

    /**
     * /** 停止录音
     */
    public void stopRecord() {
        handler.removeCallbacks(stopRecordRunnable);
        stopRecordView();
        //iEvaluateEngine.stop();
        try {
            if (mp3Recorder != null) {
                mp3Recorder.stop();
                mp3Recorder = null;
            }

        } catch (RuntimeException e) {
            if (mp3Recorder != null) {
                mp3Recorder.stop();
                mp3Recorder = null;
            }

            File file = new File(audioPath);
            if (file.exists())
                file.delete();
        }
        // iEvaluateEngine.stop();
        //stopRecordView();
        setAudioImg();
    }

    public void setAudioImg() {
        if (!"".equals(audioPath) && null != audioPath) {
            String audiolong = getDuration(audioPath);
            if ("00:00".equals(audiolong)) {
                audioPath = "";
                ToastUtil.INSTANCE.toastCenterError("录音未成功，请重试");
            } else {
                user_dk_audios_submit_layout.setVisibility(View.VISIBLE);
                delete_audio_view.setVisibility(View.VISIBLE);

                user_dk_audios_text_submit.setText(getDuration(audioPath));
                delete_audio_view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                            Log.e("MediaPlayer ", "停止播放");
                            stopPlayAnimation(user_dk_audios_img_submit);
                            mediaPlayer.stop();
                            mediaPlayer.release();
                            mediaPlayer = null;
                        }
                        audioPath = "";
                        user_dk_audios_submit_layout.setVisibility(View.GONE);
                        user_dk_audio_img.setImageDrawable(UserDkSubmitActivity.this.getResources().getDrawable(R.drawable.user_dk_audio_img));
                        delete_audio_view.setVisibility(View.GONE);
                        user_dk_audio_img.setOnClickListener(UserDkSubmitActivity.this);
                        // user_dk_audio_img.setUnAutoRecordState(true);

                    }
                });
                user_dk_audio_img.setImageDrawable(this.getResources().getDrawable(R.drawable.user_dk_audio_no));
                user_dk_audio_img.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ToastUtil.INSTANCE.toastCenterError("只能上传一段音频");
                    }
                });
            }

        } else {
            user_dk_audios_submit_layout.setVisibility(View.GONE);
            user_dk_audio_img.setVisibility(View.VISIBLE);

            delete_audio_view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                }
            });

            delete_audio_view.setVisibility(View.GONE);
        }
    }

    public void stopRecordView() {
        user_dk_audio_StateView_lay.setVisibility(View.GONE);
        dk_result_submit.setVisibility(View.VISIBLE);
        //user_dk_audio_img.stopOnlyRecord();
    }

    private void stopPreviousVideo(boolean isRecord) {
        stopPlayAnimation(user_dk_audios_img);

    }

    /**
     * 录音
     */
    protected void record() {
        // 开始录音
        try {

            user_dk_audio_StateView.setTimeCount((long) 180000);
            user_dk_audio_StateView.startUnAutoRecord();
            startRecord();
            // 开始线程，停止录音
            handler.postDelayed(stopRecordRunnable, 180000
            );
        } catch (OutOfMemoryError error) {
            isRecord = false;
            error.getStackTrace();
        }

    }

    private final int CODE_REQUEST_WRITESD_PERMISSION = 8800;

    /**
     * 加载视频视图
     */
    private void initVideoView() {
        IVUtils.setImageWidth200(user_dk_video_submit.thumbImageView, null);
        IVUtils.setImageWidth200(user_commit_video.thumbImageView, null);
        showGetSDcardPermissDialog();
    }

    private CWDialog getSDcardPermissDialog;

    /**
     * 获取SDcard权限提示框
     */
    private boolean showGetSDcardPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (Build.VERSION.SDK_INT < 23 || isHavePermiss) {
            checkSDcardpermiss();
        } else {
            if (getSDcardPermissDialog == null) {
                getSDcardPermissDialog = new CWDialog(this);
                getSDcardPermissDialog.setTitle(R.string.get_permiss_title);
                getSDcardPermissDialog.setTitleTextColor(Color.BLACK);
                getSDcardPermissDialog.setMessage(getString(R.string.get_sdcard_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getSDcardPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                        checkSDcardpermiss();
                    }
                });
                getSDcardPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                    }
                });
            }
            getSDcardPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用sd卡，判断权限
     */
    private boolean checkSDcardpermiss() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读写本地存储权限");
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_WRITESD_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                initDataView();
                            }
                        }
                    });
        } else {
            initDataView();
        }
        return true;
    }

    /**
     * 设置视频播放资源
     */
    private void initDataView() {
        localVideoPath = ESystem.getDubingVideoPath() + File.separator + StringUtils.md5(videoUri);
        File targetFile = new File(localVideoPath);
        if (targetFile.exists()) {
            mKHBVideoPlayerStandard.setplsyModeUrlUp(localVideoPath, KHBVideoPlayer.SCREEN_LAYOUT_LIST, KHBVideoPlayer.PLAY_MODE_UNMUTE, "");
        } else {
            mKHBVideoPlayerStandard.setplsyModeUrlUp(videoUri, KHBVideoPlayer.SCREEN_LAYOUT_LIST, KHBVideoPlayer.PLAY_MODE_UNMUTE, "");
            downWork(videoUri, localVideoPath);
        }
        //mKHBVideoPlayerStandard.startVideo(KHBVideoPlayer.PLAY_MODE_UNMUTE);

    }

    private BaseDownloadTask task;

    FileDownloadListener fileDownloadListener = new FileDownloadListener() {

        @Override
        protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

            CWLog.d("down", "down_penging");
        }


        @Override
        protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {

            CWLog.d("down", "down_connected");
        }

        @Override
        protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {

            CWLog.d("down", "down_connected");
        }

        @Override
        protected void completed(BaseDownloadTask task) {
        }

        @Override
        protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

        }

        @Override
        protected void error(BaseDownloadTask task, Throwable e) {
            task.cancel();
        }

        @Override
        protected void warn(BaseDownloadTask task) {
            CWLog.d("down", "down_warn");

        }
    };

    public void downWork(String videoUrl, String localVideoPath) {
        //下载视频
        try {
            FileDownloader mFileDownloader = FileDownloader.getImpl();
            mFileDownloader.setMaxNetworkThreadCount(2);
            if (null != task && task.isRunning()) {
                task.cancel();
            }
            task = mFileDownloader.create(videoUrl)
                    .setPath(localVideoPath)
                    .setAutoRetryTimes(3)
                    .setTag(videoUrl)
                    .setForceReDownload(true)
                    .setListener(fileDownloadListener);
            task.start();
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (null != savedInstanceState) {
            subVideoPath = savedInstanceState.getString("subVideoPath");
            audioPath = savedInstanceState.getString("audioPath");
            editText = savedInstanceState.getString("editText");
            uriList = (List<String>) savedInstanceState.getSerializable("uriList");
            subPicList = (List<String>) savedInstanceState.getSerializable("subPicList");
            setSubmitImg();
            setSubVideo();
            setAudioImg();
            user_dk_edit_work.setText(editText);
        }
    }

    @Override   //保存activity状态数据，数据在内存中，Bundle类型存着
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.i("main", "onSaveInstanceState()");
        outState.putString("subVideoPath", subVideoPath);
        outState.putString("audioPath", audioPath);
        outState.putString("editText", editText);
        outState.putSerializable("uriList", (Serializable) uriList);
        outState.putSerializable("subPicList", (Serializable) subPicList);
    }

    @Override  //恢复内存中的数据
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Log.i("main", "onRestoreInstanceState()");
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            Log.e("MediaPlayer ", "停止播放");
            stopPlayAnimation(user_dk_audios_img);
            stopPlayAnimation(user_commit_audios_img);
            stopPlayAnimation(teacher_commit_audios_img);
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        if (timer != null) {
            timer.cancel();
        }
        KHBVideoPlayer.releaseAllVideos();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        /*handler.removeCallbacks(startRunnable);
        handler.removeCallbacks(stopRunnable);*/
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            Log.e("MediaPlayer ", "停止播放");
            stopPlayAnimation(user_dk_audios_img);
            stopPlayAnimation(user_commit_audios_img);
            stopPlayAnimation(teacher_commit_audios_img);
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;

        }
        if (null != mediaRecorder) {
            mediaRecorder.stop();
            mediaRecorder.release();
        }
        if (timer != null) {
            timer.cancel();
        }
        mRecorderHandler.removeCallbacksAndMessages(null);
        KHBVideoPlayer.releaseAllVideos();
        ALiYunManager.getInstance().unRegisterListener(aLiYunListener);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            //editText =  user_dk_edit_work.getText().toString();
            if (mKHBVideoPlayerStandard.isViewPostVideo) {
                return true;
            } else if (!"".equals(subVideoPath) || !"".equals(audioPath) || subPicList.size() != 0 || !"".equals(editText)) {
                final CWDialog cwDialog = new CWDialog(UserDkSubmitActivity.this);
                cwDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        cwDialog.dismiss();
                    }
                });
                cwDialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        cwDialog.dismiss();
                        finish();
                    }
                });
                cwDialog.setMessage("是否放弃编辑内容", 16, Color.BLACK);
                cwDialog.show();
                return true;
            } else {
                return super.onKeyDown(keyCode, event);
            }


        } else {
            return super.onKeyDown(keyCode, event);
        }

    }
}
